/*
 * Copyright 2013 Glassy Cinema.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package hu.glassy.web.panel.account.registration;

import hu.glassy.core.model.Account;
import hu.glassy.core.service.AccountService;
import hu.glassy.web.auth.ApplicationSession;
import hu.glassy.web.component.common.CustomAjaxSubmitLink;
import hu.glassy.web.component.feedback.CustomFeedbackPanel;
import hu.glassy.web.component.visitor.ErrorMessageFormVisitor;
import hu.glassy.web.error.ActivationTokenException;
import hu.glassy.web.page.home.UserHomePage;
import hu.glassy.web.panel.common.CustomPanel;
import hu.glassy.web.util.Constants;
import hu.glassy.web.util.PasswordHelper;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.feedback.ComponentFeedbackMessageFilter;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;
import org.apache.wicket.validation.validator.EmailAddressValidator;
import org.apache.wicket.validation.validator.PatternValidator;
import org.apache.wicket.validation.validator.StringValidator;

/**
 *
 * @author molnaralexander
 */
public class RegistrationGlassyPanel extends CustomPanel<Account>
{

  @SpringBean
  private AccountService accountService;

  /**
   * Simple constructor with the component ID. The model object will be a new
   * Account.
   *
   * @param id
   */
  public RegistrationGlassyPanel(String id)
  {
    this(id, Model.of(new Account()));
  }

  /**
   * Constructor with component id and an account model.
   *
   * @param id
   * @param model
   */
  public RegistrationGlassyPanel(String id, final IModel<Account> model)
  {
    super(id);
    setDefaultModel(new CompoundPropertyModel<Account>(model));

    final Form<Account> form = new Form<Account>("registrationForm");
    form.add(new CustomFeedbackPanel("feedbackPanel").setFilter(new ComponentFeedbackMessageFilter(form)));

    form.add(generateEmailInput());
    form.add(generateNameInput());
    FormComponent password = generatePasswordInput();
    form.add(password);
    FormComponent cpassword = generateConfirmInput();
    form.add(cpassword);
    form.add(new EqualPasswordInputValidator(password, cpassword));
    form.add(generateSubmitButton());

    form.visitChildren(new ErrorMessageFormVisitor<String>());
    add(form);
  }

  private Component generateSubmitButton()
  {
    return new CustomAjaxSubmitLink("submitButton")
    {
      private static final long serialVersionUID = 8775028623062298638L;

      @Override
      protected void onSubmit(final AjaxRequestTarget target, final Form<?> form)
      {
        super.onSubmit(target, form);

        onFormSubmit(target, RegistrationGlassyPanel.this.getmainModel());
      }
    };
  }

  private FormComponent<String> generateEmailInput()
  {
    FormComponent<String> emailField = new TextField<String>("email");
    emailField.setRequired(true);
    emailField.add(EmailAddressValidator.getInstance());
    emailField.add(generateEmailValidator());
    emailField.add(StringValidator.maximumLength(Account.EMAIL_LENGTH));
    return emailField;
  }

  private FormComponent<String> generateNameInput()
  {
    final TextField<String> input = new TextField<String>("name");
    input.setRequired(true);
    input.add(StringValidator.maximumLength(Account.NAME_LENGTH));
    return input;
  }

  private FormComponent<String> generatePasswordInput()
  {
    PasswordTextField passwordField = new PasswordTextField("password");
    passwordField.setRequired(true);
    passwordField.setResetPassword(false);
    passwordField.add(new PatternValidator(Constants.PASSWORD_PATTERN));
    return passwordField;
  }

  private FormComponent<String> generateConfirmInput()
  {
    PasswordTextField confirmField = new PasswordTextField("cpassword", Model.of(""));
    confirmField.setRequired(true);
    confirmField.setResetPassword(false);
    return confirmField;
  }

  private IValidator<String> generateEmailValidator()
  {
    return new IValidator<String>()
    {
      private static final long serialVersionUID = -8522982733849492932L;

      public void validate(final IValidatable<String> validatable)
      {
        final String email = validatable.getValue();
        if (ApplicationSession.get().isSignedIn())
        {
          final Account current = ApplicationSession.get().getAccount().getObject();
          if (email.equals(current.getEmail()))
          {
            return;
          }
        }

        if (accountService.isEmailAddressInUse(email))
        {
          ValidationError validationError = new ValidationError();
          validationError.setMessage(getString("registration.error.email.inuse"));
          validatable.error(validationError);
        }
      }
    };
  }

  public void onFormSubmit(final AjaxRequestTarget target, final IModel<Account> model)
  {
    try
    {
      startReqistration(model.getObject());
    }
    catch (final ActivationTokenException e)
    {
      error(e.getMessage());
    }
  }

  private void startReqistration(final Account account) throws ActivationTokenException
  {
    // Encrypt the password...
    account.setPassword(PasswordHelper.encrypt(account.getPassword()));

    // Save the user data...
    accountService.registration(account);

    // Notify the user about the successfull registration...
    getSession().success(getString("registration.success"));

    // If an activation is required, notify the user...
    if (!account.isActive())
    {
      getSession().info(getString("registration.success.activation"));
    }

    // Log in the user with the new account
    AuthenticatedWebSession.get().signIn(account.getEmail(), account.getPassword());

    // Redirect the user to the homepage
    setResponsePage(UserHomePage.class);
  }
}
